import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:domain/model/banner_domain_model.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class BannerLayout extends StatefulWidget {
  final RxList<BannerDomainModel> bannerModels;
  final Function(String, String) onClickImage;

  const BannerLayout({
    super.key,
    required this.bannerModels,
    required this.onClickImage,
  });

  @override
  State<StatefulWidget> createState() => _BannerLayoutState();
}

class _BannerLayoutState extends State<BannerLayout> {
  final PageController _pageController = PageController();
  int _currentPage = 0;
  late Timer _timer;

  @override
  Widget build(BuildContext context) {
    return Obx(
      () => PageView.builder(
        controller: _pageController,
        itemCount: widget.bannerModels.length,
        itemBuilder: (_, index) {
          final item = widget.bannerModels[index];
          return CachedNetworkImage(
            fit: BoxFit.cover,
            imageUrl: item.imageUrl,
            progressIndicatorBuilder: (context, url, downloadProgress) =>
                CircularProgressIndicator(
                  value: downloadProgress.progress,
                ).center(),
            errorWidget: (context, url, error) => Icon(Icons.error),
          ).onTap(behavior: HitTestBehavior.opaque, () {
            widget.onClickImage(item.title, item.url);
          });
        },
        onPageChanged: (index) {
          setState(() {
            _currentPage = index;
          });
        },
      ),
    ).constrained(width: double.infinity, height: 100.h);
  }

  @override
  void dispose() {
    _pageController.dispose();
    _timer.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(const Duration(seconds: 10), (_) {
      final newPage = _getCurrentPageIndex(_getMaxSize());
      setState(() {
        _currentPage = newPage;
      });

      if (_pageController.hasClients) {
        _pageController.animateToPage(
          newPage,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
        );
      }
    });
  }

  int _getCurrentPageIndex(int maxSize) {
    return (_currentPage < maxSize - 1) ? _currentPage + 1 : 0;
  }

  int _getMaxSize() => widget.bannerModels.length;
}
